package com.zhugang.week04;

/**
 * @program algorithms
 * @description: sortList
 * @author: chanzhugang
 * @create: 2022/06/30 15:01
 */
public class SortList2 {

    /**
     * 排序链表
     *
     * @param head
     * @return
     */
    public ListNode sortList(ListNode head) {
        // 归并排序链表
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }
        ListNode midNode = findMidNode(head);
        ListNode nextNode = midNode.next;
        midNode.next = null;
        ListNode leftHead = sortList(head);
        ListNode rightHead = sortList(nextNode);
        return mergeList(leftHead, rightHead);

    }

    /**
     * 合并两个有序链表
     *
     * @param list1
     * @param list2
     * @return
     */
    private ListNode mergeList(ListNode list1, ListNode list2) {
        // 合并两个有序链表
        ListNode newHead = new ListNode();
        ListNode tail = newHead;
        ListNode p1 = list1;
        ListNode p2 = list2;
        while (p1 != null && p2 != null) {
            if (p1.val <= p2.val) {
                tail.next = p1;
                tail = p1;
                p1 = p1.next;
            } else {
                tail.next = p2;
                tail = p2;
                p2 = p2.next;
            }
        }
        if (p1 != null) {
            tail.next = p1;
        }
        if (p2 != null) {
            tail.next = p2;
        }
        return newHead.next;
    }

    /**
     * 链表中间节点
     *
     * @param head
     * @return
     */
    private ListNode findMidNode(ListNode head) {
        // 快慢指针找中间节点
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}